//
//  MBRecomController.m
//  mibaotu
//
//  Created by 彭鹏 on 16/9/17.
//  Copyright © 2016年 pegnk. All rights reserved.
//

#import "MBRecomController.h"
#import "MBShowCell.h"
#import "MBDetailViewController.h"
#import "MBSpacePeopelViewController.h"
#import "MBSpaceNewsViewController.h"
#import "MBSongDetailController.h"
#import "MBLoginController.h"

@interface MBRecomController ()<UITableViewDataSource,UITableViewDelegate,MBShowCellDelegate>
{
    int                 page;
    MBShowCell          *_showCell;
    BOOL                selected;
    NSMutableArray      *_mutArr;
    float               nHeight;
}


@property(nonatomic,strong)NSMutableArray *dataArray;
@end

@implementation MBRecomController
- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    page = 1;
    _mutArr = [[NSMutableArray alloc]init];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [_tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(onLoadNew)];
    [_tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(onLoadMore)];
    if (nHeight > 0) {
        [self onUPdateUIForTable:nHeight];
    }
    
    if ([_sortStr isEqualToString:@"2"]) {
        [self onLoadNew];
    }
}


- (void)reloadSearchData_keyword:(NSString *)keyword office:(NSString *)office
{

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self onLoadNew];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

}

#pragma mark - 加载数据

- (void)onLoadNew
{
    page = 1;
    [self loadData];
}

- (void)onLoadMore
{
    ++page;
    [self loadData];
}

- (void)loadData
{
    NSString *url = nil;
    UserModel *model = [UserManager standerDefult].userModel;
    
    if ([_sortStr isEqualToString:@"1"]) {
        //小编推荐
        url = [NSString stringWithFormat:FAMILYSHOW_FANSMORE_URL_PATH,model.UserID,[NSNumber numberWithInt:page]];
    }
    else if ([_sortStr isEqualToString:@"2"]) {
        //我的关注
        UserModel *model = [UserManager standerDefult].userModel;
        if (!model.UserID) {
//            MBLoginController *registerLastVC = [[MBLoginController alloc] init];
//            registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
//            [self.navigationController pushViewController:registerLastVC animated:YES];
            
            [_tableView.header endRefreshing];
            [_tableView.footer endRefreshing];
            return;
        }
        
        url = [NSString stringWithFormat:FAMILYSHOW_MYATTENTION_URL_PATH,model.UserID,[NSNumber numberWithInt:page]];
    } else {
        return;
    }
    
    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        
        if ([json[@"ret_code"] integerValue]==0) {
            NSArray *arr = json[@"data"];
            if (arr.count > 0) {
                if (page == 1) {
                    [_mutArr removeAllObjects];
                }
                [_mutArr addObjectsFromArray:arr];
            }
            [_tableView reloadData];
        } 
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        if (page == 1) {
            [_mutArr removeAllObjects];
        }
        [_tableView reloadData];
    }];
}

- (void)onUPdateUIForTable:(float)height
{
    nHeight = height;
    _tableView.height = nHeight;
    [_tableView reloadData];
}

#pragma mark - 结束编辑


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _mutArr.count;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MBShowCell *showCell = [MBShowCell cellWithTableView:tableView];
    showCell.delegate = self;
    showCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (_mutArr.count > indexPath.row) {
        NSDictionary *dic = [_mutArr objectAtIndex:indexPath.row];
        BOOL isZan = [[dic objectForKey:@"PraiseStatus"]boolValue];
        
        showCell.isZan = isZan;
        showCell.dateDic = dic;
    }
    
    return showCell;
    
}


- (void)onSelectIconBtnWithView:(MBShowCell *)view withDataDic:(NSDictionary *)value {

    
//    if ( self.delegate != nil && [self.delegate respondsToSelector:@selector(pushSubViewController:)]) {
    
//        UserModel *model = [UserManager standerDefult].userModel;
//        if (!model) {
            MBSpacePeopelViewController *spacePeopleVC = [[MBSpacePeopelViewController alloc] init];
            spacePeopleVC.dateDic = value;
            [self.navigationController pushViewController:spacePeopleVC animated:YES];
//        } else {
//            NSString *userID = [value objectForKey:@"UserID"];
//            if ([userID intValue] == [model.UserID intValue]) {
//                
//            } else {
//                MBSpacePeopelViewController *spacePeopleVC = [[MBSpacePeopelViewController alloc] init];
//                spacePeopleVC.dateDic = value;
//                [self.delegate pushSubViewController:spacePeopleVC];
//            }
//        }
        
        
        
//    }
    _showCell = view;
}

#pragma mark - 点赞
-(void)onSelectPraiseBtnWithView:(MBShowCell *)view withValue:(NSDictionary *)value{
    
    UserModel *model = [UserManager standerDefult].userModel;
    if (!model.UserID) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }
    
    if (![value isKindOfClass:[NSDictionary class]]) return;
    
    if (!model) return;
    
    //区分点赞或取消点赞
    NSString *PraiseStatus = [NSString stringWithFormat:@"%@",[value objectForKey:@"PraiseStatus"]];
    NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:value];
    int indexMut = (int)[_mutArr indexOfObject:value];
    if ([PraiseStatus boolValue] == YES) {
        //取消点赞
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_CANCEL_ZAN_URL_PATH,model.UserID,[value objectForKey:@"ID"],@1] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                //取消点赞成功
                if (_mutArr.count > indexMut && indexMut >= 0) {
                    MBShowCell *cell = (MBShowCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:indexMut inSection:0]];
                    if ([cell isKindOfClass:[MBShowCell class]]) {
                        [cell onUpdateZanBtAction:NO];
                    }
                }
                
                //数据更新
                [mutDic setValue:[NSNumber numberWithInt:([[value objectForKey:@"PraiseNum"] intValue]-1)] forKey:@"PraiseNum"];
                [mutDic setValue:@0 forKey:@"PraiseStatus"];
                if (indexMut < _mutArr.count && indexMut >= 0) {
                    [_mutArr replaceObjectAtIndex:indexMut withObject:mutDic];
                    [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexMut inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                }
                
                
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    } else  {
        //点赞
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_ZAN_URL_PATH,model.UserID,[value objectForKey:@"ID"],@1] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                //点赞成功
                if (_mutArr.count > indexMut && indexMut >= 0) {
                    MBShowCell *cell = (MBShowCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:indexMut inSection:0]];
                    if ([cell isKindOfClass:[MBShowCell class]]) {
                        [cell onUpdateZanBtAction:YES];
                    }
                }
                
                //数据更新
                [mutDic setValue:[NSNumber numberWithInt:([[value objectForKey:@"PraiseNum"] intValue]+1)] forKey:@"PraiseNum"];
                [mutDic setValue:@1 forKey:@"PraiseStatus"];
                if (indexMut < _mutArr.count && indexMut >= 0) {
                    [_mutArr replaceObjectAtIndex:indexMut withObject:mutDic];
                    [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexMut inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                }
                
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 305;//320;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //1.取消选中这行
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //NewsModel *newsModel = [self.dataArray objectAtIndex:indexPath.row];
//    if ( self.delegate != nil && [self.delegate respondsToSelector:@selector(pushSubViewController:)]) {
#pragma mark - 亲子秀iphone播放器 标准
        UserManager *manager = [UserManager standerDefult];
        
        NSString *idStr ;
        if (manager.audioPlayerType != AudioPLayerType_Qinzix) {
            //初次进入
            idStr = @"";
            manager.audioPlayerType = AudioPLayerType_Qinzix;
        } else {
            //2次进入
            NSInteger selectIndex = manager.selectMusicIndex;
            NSArray *arr = manager.musicArr;
            if (arr.count > selectIndex) {                
                Music *dics = [arr objectAtIndex:selectIndex];
                idStr = [NSString stringWithFormat:@"%@",dics.ID];
            }
        }
        [manager setSelectMusicIndex:indexPath.row];
        [manager.musicArr removeAllObjects];
        [manager.musicArr addObjectsFromArray:[manager onTurnArrayFormQingZiXiuArray:_mutArr]];
        manager.selectMusicIndex = indexPath.row;
        [manager.qinzixiuArr removeAllObjects];
        [manager.qinzixiuArr addObjectsFromArray:_mutArr];
        
        MBDetailViewController *childShowVC = [[MBDetailViewController alloc] init];
        [childShowVC.dataAllArr addObjectsFromArray:_mutArr];
        childShowVC.selectMusicID = idStr;
        [self.navigationController pushViewController:childShowVC animated:YES];
        
//    }
}

#pragma mark - ScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float y = scrollView.contentOffset.y;
    //    NSLog(@"滑动位移:%.2f",y);
    if (y > 0 && y < 276*PERCEN*2) {
        //隐藏
        if (self.onRecomUIForBlock) {
            if (y >= 276*PERCEN) y = 276*PERCEN;
            self.onRecomUIForBlock(y);
            NSLog(@"隐藏位移:%.2f",y);
        }
    }
    else if ((y < 0 && y > -276*PERCEN)) {
        //显示
        if (self.onRecomUIForBlock) {
            if (y <= 0) y = 0;
            self.onRecomUIForBlock(y);
            //             NSLog(@"****显示位移:%.2f",y);
        }
    }
}

@end
